package com.xq.sboot.servlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.Date;

/**
 * 功能说明: 第一个Filter类.
 * <p>创建时间:2018-12-14 10:51</p>
 *
 * @author <a href="https://gitee.com/gkq/microservice">郭凯强</a>
 * @since 1.0.0
 */
@WebFilter(urlPatterns = "/*", filterName = "log-filter")
public class FirstFilter implements Filter {
    private final Logger logger = LoggerFactory.getLogger(FirstFilter.class);
    private final Marker marker = MarkerFactory.getMarker("FirstFilter");

    /**
     * FilterConfig用于访问Filter的配置信息
     */
    private FilterConfig filterConfig = null;

    /**
     * 实现初始化方法
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        logger.debug(marker, "初始化Filter={}", FirstFilter.class.getName());
    }

    /**
     * 实现销毁方法
     */
    @Override
    public void destroy() {
        logger.debug(marker, "销毁Filter={},销毁时刻={}", this.filterConfig.getFilterName(), new Date());
    }

    /**
     * 执行过滤的核心方法
     *
     * @param request  请求对象
     * @param response 响应对象
     * @param chain    处理请求的Filter链
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        logger.debug(marker, "Filter={}开始过滤请求的时间={}", FirstFilter.class.getName(), new Date());
        // Filter采用链式处理, 最后将请求放行到目的地址
        chain.doFilter(request, response);
        logger.debug(marker, "Filter={}结束过滤请求的时间={}", FirstFilter.class.getName(), new Date());

    }
}
